<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>正六边形</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <canvas id="hexagon"></canvas>
    <script>
      function drawHexagon(
        ctx,
        centerX,
        centerY,
        size,
        borderColor,
        fillColor,
        text,
        fontColor = "#000"
      ) {
        ctx.beginPath();
        ctx.moveTo(centerX + size, centerY);
        // 设置描边
        ctx.strokeStyle = borderColor;
        ctx.fillStyle = fillColor;
        for (let i = 1; i < 6; i++) {
          ctx.lineTo(
            centerX + size * Math.cos((2 * Math.PI * i) / 6),
            centerY + size * Math.sin((2 * Math.PI * i) / 6)
          );
        }
        ctx.closePath();
        ctx.fill();
        ctx.stroke();

        // 准备绘制文字
        ctx.font = "bold 24px sans-serif"; // 设置字体样式
        ctx.fillStyle = fontColor; // 设置填充颜色为白色
        const metrics = ctx.measureText(text);
        const textWidth = metrics.width;
        const textHeight = 24; // 字体高度

        // 文字居中
        const textX = centerX - textWidth / 2;
        const textY = centerY + textHeight / 2; // y坐标调整以垂直居中

        // 绘制文字
        ctx.fillText(text, textX, textY);
        ctx.stroke();
      }

      const canvas = document.getElementById("hexagon");
      const ctx = canvas.getContext("2d");

      // 设置画布大小
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
      // 绘制多个正六边形
      const hexSize = 50; // 正六边形的大小
      const spacing = hexSize * Math.cos(2 * Math.PI) * 3; // 水平间距
      const verticalSpacing = hexSize * Math.sin((2 * Math.PI) / 6); // 垂直间距
      const x = 50;
      const y = 50;
      // 绘制正六边形
      drawHexagon(ctx, x, y, hexSize, "#f00");
      // 在正六边形周围绘制多个正六边形
      for (let col = 0; col < 5; col++) {
        for (let row = 0; row < 10; row++) {
          drawHexagon(
            ctx,
            x + col * spacing + ((row % 2) * spacing) / 2,
            y + row * verticalSpacing,
            hexSize,
            "#f00",
            "#ffa",
            `${row}-${col}`
          );
        }
      }
    </script>
  </body>
</html>
